/*
 * MLObject.java
 * Copyright January 26, 2013 Erik Strelzoff
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.magelord.model;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.magelord.utils.JSONUtil;

/**
 * Superclass of all MageLord data objects
 */
public abstract class MLObject {
	
	protected final String m_className;
	
	public MLObject() {
		m_className = getClass().getName();
	}
	
	public String getClassName() {
		return m_className;
	}
	
	public static MLObject fromJson(String jsonText, Gson gson) throws ClassCastException, ClassNotFoundException {
		// Create an MLObject from the ClassName.
		// Fill with data fields from the jsonObject
		
		// First parse the Json into a generic JsonObject.
		JsonObject jobj = (JsonObject)gson.fromJson(jsonText, JsonElement.class);
		
		// Then pull out the m_className parameter to figure out what kind of
		// MLObject this is.
		JsonElement classNameElem = jobj.get("m_className");
		
		// No classname?  Then we can't cast this object to an MLObject.
		if (classNameElem == null) throw new ClassCastException("json object does not specify m_classname");
		
		String className = classNameElem.getAsJsonPrimitive().getAsString();
		Class cl = Class.forName(className);

		// Finish deserialization into the target object.
		return (MLObject)gson.fromJson(jobj, cl);
	}
}
